package com.atguigu.yygh.orders.controller;

import com.atguigu.yygh.common.result.R;
import com.atguigu.yygh.handler.YyghException;
import com.atguigu.yygh.orders.service.PaymentInfoService;
import com.atguigu.yygh.orders.service.WeixinService;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/api/order/weixin")
public class WeixinController {
    @Autowired
    private WeixinService weixinPayService;

    @Autowired
    private PaymentInfoService paymentInfoService;
    /**
     * 下单 生成二维码
     */
    @GetMapping("/createNative/{orderId}")
    public R createNative(
            @ApiParam(name = "orderId", value = "订单id", required = true)
            @PathVariable("orderId") Long orderId) {
        Map map = weixinPayService.createNative(orderId);
        return R.ok().data(map);
    }



    @ApiOperation(value = "查询支付状态")
    @GetMapping("/queryPayStatus/{orderId}")
    public R queryPayStatus(
            @ApiParam(name = "orderId", value = "订单id", required = true)
            @PathVariable("orderId") Long orderId)
    {
        Map<String,String> map = weixinPayService.queryPayStatus(orderId, "2");
        if (null== map){
            throw new YyghException(20001,"支付失败");
        }

        if ("SUCCESS".equals(map.get("trade_state"))){
            //支付成功
            String outTradeNo =  map.get("out_trade_no");
            paymentInfoService.paySuccess(outTradeNo,2,map);

            return R.ok().message("支付成功");
        }
        return R.ok().message("待支付");
    }
}
